import { login, getUserInfo, getUserInfo2 } from "@/api/user";
import { dictAll } from "@/api/dict";
const user = {
  state: {
    userCode: "",
    oppenId: null,
    token: null,
    info: {},
    dictAll: {},
  },
  mutations: {
    SET_INFO: (state, info) => {
      state.info = info;
    },
    SET_OPPENID: (state, info) => {
      state.oppenId = info;
    },
    SET_TOKEN: (state, info) => {
      state.token = info;
    },
    SET_DICT: (state, info) => {
      state.dictAll = info;
    },
  },
  actions: {
    // 登录
    Login({ commit, dispatch }, info) {
      return new Promise((resolve, reject) => {
        login(info)
          .then((res) => {
            if (res.code === 0) {
              commit("SET_TOKEN", res.data);
              dispatch("GetdictMuster");
              dispatch("getUserInfo");
              uni.setStorageSync("xiahui-token", res.data);
            }
            resolve(res);
          })
          .catch((e) => {
            resolve(e);
          });
      });
    },
    // 登出
    LogOut({ commit }, info) {
      return new Promise((resolve, reject) => {
        uni.removeStorageSync("xiahui-token");
        commit("SET_TOKEN", null);
        resolve();
      });
    },
    getUserInfo({ commit }, info) {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin', //使用微信登录
          success: function (loginRes) {
            getUserInfo(loginRes.code).then((res) => {
              if (res.data) {
                commit("SET_TOKEN", res.data.token);
                commit("SET_INFO", res.data);
              }
              resolve(res.data);
            })
          }
        })
      });
    },
    getUserInfoIsLogin({ commit }, info) {
      return new Promise((resolve, reject) => {
        getUserInfo2().then((res) => {
          if (res.data) {
            commit("SET_INFO", res.data);
          }
          resolve(res.data);
        })
      });
    },
    //获取字典枚举
    GetdictMuster({ commit }) {
      return new Promise((resolve, reject) => {
        dictAll()
          .then((response) => {
            const result = response;
            commit("SET_DICT", result);
            resolve(result);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

export default user;
